package gdepot

import static org.springframework.http.HttpStatus.*
import grails.transaction.Transactional

@Transactional(readOnly = false)
class OrdersController {

    static allowedMethods = [save: "POST", update: "PUT", delete: "DELETE"]

    def orderService
      def index(Integer max) {
          params.max = Math.min(max ?: 10, 100)
          respond Orders.list(params), model:[ordersInstanceCount: Orders.count()]
      }

    def show(Orders ordersInstance) {
        respond ordersInstance
    }

    def create() {
        /* respond new Orders(params)*/
        def orders=new Orders(params)
        def cart=orderService.prepareCart(session)
        println "----------------"+cart+"-------------------"
        def user=cart.user
        return  [ordersInstance:orders,cart:cart]
        /* respond(model:[ordersInstance:orders,cart:cart] )*/
    }


    /* @Transactional
     def save(Orders ordersInstance) {
         if (ordersInstance == null) {
             notFound()
             return
         }

         if (ordersInstance.hasErrors()) {
             respond ordersInstance.errors, view:'create'
             return
         }

         ordersInstance.save flush:true

         request.withFormat {
             form multipartForm {
                 flash.message = message(code: 'default.created.message', args: [message(code: 'orders.label', default: 'Orders'), ordersInstance.id])
                 redirect ordersInstance
             }
             '*' { respond ordersInstance, [status: CREATED] }
         }
     }
 */
    def edit(Orders ordersInstance) {
        respond ordersInstance
    }

    @Transactional
    def update(Orders ordersInstance) {
        if (ordersInstance == null) {
            notFound()
            return
        }

        if (ordersInstance.hasErrors()) {
            respond ordersInstance.errors, view:'edit'
            return
        }

        ordersInstance.save flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.updated.message', args: [message(code: 'orders.label', default: 'Orders'), ordersInstance.id])
                redirect ordersInstance
            }
            '*'{ respond ordersInstance, [status: OK] }
        }
    }

    @Transactional
    def delete(Orders ordersInstance) {

        if (ordersInstance == null) {
            notFound()
            return
        }

        ordersInstance.delete flush:true

        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.deleted.message', args: [message(code: 'orders.label', default: 'Orders'), ordersInstance.id])
                redirect action:"index", method:"GET"
            }
            '*'{ render status: NO_CONTENT }
        }
    }

    protected void notFound() {
        request.withFormat {
            form multipartForm {
                flash.message = message(code: 'default.not.found.message', args: [message(code: 'orders.label', default: 'Orders'), params.id])
                redirect action: "index", method: "GET"
            }
            '*'{ render status: NOT_FOUND }
        }
    }

    def save(){

        def  orders=new Orders(params)
//        orders.receiverName=params.receiverName
//        orders.address=params.address
//        orders.phone=params.phone
        try{
            orderService.saveOrder(session,orders)
            flash.message=message(code:"order.save.success")
            redirect action: "mineOrders"
        }catch (Exception ex){//发生异常，返回提交页面，并报告错误信息
            flash.message=message(code:"order.save.failed")
            def cart=orderService.prepareCart(session)
//            render(view: 'create',model: [ordersInstance: orders,cart:cart])
            redirect controller: 'cart', action: 'index', params: [ordersInstance: orders,cart:cart]
        }
    }

    def mineOrders(){
        if (!params.max)
            params.max=5
//        def user=Users.get(session.userId)
        def user = session.user
        if(user){
            def orderList
            def orderCount
            params.order='desc'
            params.sort='orderDate'
            if (params.status=='new'){
                orderList=Orders.findAllByUserAndStatus(user,OrderStatus.TOBEPAID,params)
                orderCount=Orders.countByUserAndStatus(user,OrderStatus.TOBEPAID)
            } else if(params.status=='unpaid'){

                  orderList=Orders.findAllByUserAndStatusInList(user,[OrderStatus.TOBEPAID,OrderStatus.FAILED],params)
                  orderCount=orderList.size()
            }else{
                orderList=Orders.findAllByUser(user,params)
                orderCount=Orders.countByUser(user)
            }
            return [orderList: orderList,ordersCount: orderCount] //实现分页查询
        }
    }
    @Transactional
    def changeOrderStatus(){
        def orders = Orders.findById(params.orderId)
        def status = params.status
        if(orders && orders.user.id == session.user.id ){

                switch (status){
                    case 'CANCELED':
                        if(orders.status == OrderStatus.TOBEPAID || orders.status == OrderStatus.FAILED){
                            orders.status = status
                        }
                        else{
                            flash.message = "当前订单不允许修改"
                        }
                        break;
                    case 'SHIPPED': if(orders.status == OrderStatus.SUCCESS){
                            orders.status = status
                        }
                        else{
                             flash.message = "当前订单不允许修改"
                    }
                    case 'RECEIVED': if(orders.status == OrderStatus.SHIPPED){
                        orders.status = status
                    }
                    else{
                        flash.message = "当前订单不允许修改"
                    }
                }

                if(orders.validate())
                {
                    orders.save flush:true
                    flash.message = "订单取消成功"
                }
               else
                {
                    flash.message = "订单取消失败"
                }
        }

      render view: 'show',model: [ordersInstance:orders]
    }

}
